package org.spider.spiderweb.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spider.api.domain.vo.TaskVo;
import org.spider.api.domain.model.Notice;
import org.spider.api.domain.model.SpiderFlow;
import org.spider.api.domain.utilDomain.Result;
import org.spider.core.service.NoticeService;
import org.spider.core.service.SpiderFlowService;
import org.spider.core.service.TaskService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.File;
import java.util.Map;

@RestController
@RequestMapping("/flow")
public class FlowController {
    @Resource
    private SpiderFlowService spiderFlowService;
    @Resource
    private NoticeService noticeService;
    @Resource
    private TaskService taskService;
    @Value("${spider.workplace}")
    private String workplace;
    private static final Logger log = LoggerFactory.getLogger(FlowController.class);

    //============================================flow信息==============================================
    @GetMapping("/list")
    public Result getSpiderFlowList(@RequestParam(name = "page", defaultValue = "1") Integer page,
                                    @RequestParam(name = "limit", defaultValue = "5") Integer limit,
                                    @RequestParam(name = "name", defaultValue = "") String name) {
        return Result.getInstance(spiderFlowService.selectPage(new Page<>(page, limit), name));
    }

    @GetMapping("/getOne/{flowId}")
    public Result getSpiderFlow(@PathVariable String flowId) {
        if (flowId == null) return Result.getInstance(null);
        return Result.getInstance(spiderFlowService.selectById(flowId));
    }

    @PutMapping
    public Result saveOrUpdateFlow(@RequestBody SpiderFlow flow) {
        log.info(flow.toString());
        boolean flag = spiderFlowService.saveOrUpdateFlow(flow);
        if (flag) return Result.getInstance(spiderFlowService.selectById(flow.getId()));
        return Result.getInstance(false);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable String id) {
        boolean flag = spiderFlowService.removeById(id);
        return Result.getInstance(flag);
    }

    @DeleteMapping
    public Result deleteBatch(@RequestBody String[] ids) {
        return null;
    }


    //============================================task信息==============================================
    @GetMapping("/taskList")
    public Result getTaskList(@RequestParam(name = "page", defaultValue = "1") Integer page,
                              @RequestParam(name = "limit", defaultValue = "1") Integer limit,
                              @RequestParam(name = "flowId", defaultValue = "") String flowId,
                              @RequestParam(name="name") String name) {
//        IPage<Task> list = taskService.selectPages(new Page<>(page, limit), flowId,name);
//        PageDto pageDto = taskService.selectTaskPages(page, limit, flowId, name);
        IPage<TaskVo> taskVoIPage = taskService.selectPages(new Page<>(page, limit), flowId, name);
        return Result.getInstance(taskVoIPage);
    }

    @DeleteMapping("/deleteRecord")
    public Result deleteRecord(@RequestParam("flowId") String flowId,
                               @RequestParam("taskId") Integer id) {
        boolean flag = taskService.removeById(id);
        // 删除对应日志文件
        try {
            File file = new File(workplace, flowId + File.separator + "logs" + File.separator +
                    id + ".log");
            file.delete();
            return Result.getInstance(flag ? 1 : 0, "success,日志文件删除成功");
        } catch (Exception e) {
            return Result.getInstance(flag ? 1 : 0, "日志文件删除失败");
        }

    }

    //============================================通知信息==============================================
    @PostMapping("/notice")
    public Result saveOrUpdate(@RequestBody Notice notice) {
        if (notice == null || notice.getId() == null) return Result.getInstance(false);
        boolean flag = noticeService.saveOrUpdate(notice);
        return Result.getInstance(flag);
    }

    @GetMapping("/notice/{flowId}")
    public Result getNotice(@PathVariable String flowId) {
        if (StringUtils.isEmpty(flowId)) return Result.getInstance(false);
        Notice notice = noticeService.getById(flowId);
        return Result.getInstance(notice == null ? new Notice(flowId) : notice);
    }


    //============================================测试==============================================
    @PostMapping("/testJson")
    public Result testJson(@RequestBody Map<String, Object> map) {
        System.out.println(map);
        return Result.getInstance(map);
    }

    @PostMapping("/testJsonMap")
    public Result testJsonMap(@RequestBody JSONObject object) {
        log.info("testJsonMap->传入的json对象:{}", object);
        return Result.getInstance(object);
    }
}
